package com.aliyun.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.bean.ResultAddress;



public class HttpClientUtil {
	private RequestConfig requestConfig = RequestConfig.custom()
			.setSocketTimeout(5000).setConnectTimeout(5000)
			.setConnectionRequestTimeout(5000).setRedirectsEnabled(false).build();

	private static HttpClientUtil instance = null;

	private HttpClientUtil() {
	}

	public static HttpClientUtil getInstance() {
		if (instance == null) {
			instance = new HttpClientUtil();
		}
		return instance;
	}
	public String checkInetAddress(Map<String, Object> map){
		String status = "0";
		String stringOne = "http://"+getIP(map.get("name")+"")+":80";
		String stringTwo = "http://"+map.get("address")+":80";
		
		//
		
		if(stringOne.equals(stringTwo)){
			status = "1";
		}
		if(!stringOne.equals(stringTwo)){
			status = "2";
		}
		return status;
	}
	public String  getIP(String name){
		   InetAddress address = null;
		try {
			address = InetAddress.getByName(name);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return address.getHostAddress().toString();
	}
	
	public ResultAddress checkInetAddressS(Map<String, Object> map){
		String status = "2";
		String stringTwo = map.get("address")+"";
		ResultAddress ra = new ResultAddress();
		String stringOne = "";
		try {
			InetAddress[] address = InetAddress.getAllByName(map.get("name")+"");
			if(address!=null && address.length>0){
				for(InetAddress add : address){
					stringOne = add.getHostAddress().toString();
					System.out.println(stringOne);
					if(stringOne.equals(stringTwo)){
						status = "1";
						break;
					}
				}
			}
			ra = sendHttpsGet(map.get("name")+"");
			System.out.println("statusCode---------"+ra.getStatusCode());
			System.out.println("location---------"+ra.getLocation());
			if(ra.getStatusCode()==0){
				status = "5";
			}
			if(ra.getStatusCode()==301||ra.getStatusCode()==302){
				status = "4";
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if("2".equals(status)){
			//根据ip去获取域名
			String[] ipStr=stringOne.split("[.]");         //IP地址转换为字符串数组  
            byte[] ipBytes=new byte[4];             //声明存储转换后IP地址的字节数组  
            for (int i = 0; i < 4; i++) {  
                int m=Integer.parseInt(ipStr[i]);   //转换为整数  
                byte b=(byte)(m&0xff);              //转换为字节  
                ipBytes[i]=b;  
            }  
            InetAddress inetAddr;
			try {
				inetAddr = InetAddress.getByAddress(ipBytes);
				String canonical=inetAddr.getHostName(); 
				ra.setLocation(canonical);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} //创建InetAddress对象  
            
		}
		ra.setStatus(status);
		return ra;
	}
//	public String sendHttpsGet(String httpUrl) {
//		HttpGet httpGet = new HttpGet(httpUrl);
//		setHttpGetHeader(httpGet);
//		return sendHttpsGet(httpGet);
//	}
	public void updateYuMingList(String httpUrl,Map<String,String> maps){
		HttpPost httpPost = new HttpPost(httpUrl);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        for (String key : maps.keySet()) {  
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
        }  
        try {  
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
		updateYuMingList(httpPost);
	}
	public List<Map<String,Object>> getYuMingList(String httpUrl){
		HttpGet httpGet = new HttpGet(httpUrl);
		return getYuMingList(httpGet);
		
	}
	public ResultAddress sendHttpsGet(String httpUrl) {
		HttpGet httpGet = new HttpGet("http://"+httpUrl);
		setHttpGetHeader(httpGet,httpUrl);
		return sendHttpsGet(httpGet);
	}
	private HttpGet setHttpGetHeader(HttpGet httpGet,String httpUrl) {
		httpGet.addHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
		httpGet.addHeader("Accept-Language", " zh-CN,zh;q=0.8");
		httpGet.addHeader("Connection", " keep-alive");
		httpGet.addHeader("Host", httpUrl);
		
		httpGet.addHeader(
				"User-Agent",
				" Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		return httpGet;
	}
//	private String sendHttpsGet(HttpGet httpGet) {
//		CloseableHttpClient httpClient = null;
//		CloseableHttpResponse response = null;
//		HttpEntity entity = null;
//		String responseContent = null;
//		try {
//			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
//					.load(new URL(httpGet.getURI().toString()));
//			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(
//					publicSuffixMatcher);
//			httpClient = HttpClients.custom()
//					.setSSLHostnameVerifier(hostnameVerifier).build();
//			httpGet.setConfig(requestConfig);
//			response = httpClient.execute(httpGet);
//			int status = response.getStatusLine().getStatusCode();
//			entity = response.getEntity();
//			responseContent = EntityUtils.toString(entity, "UTF-8");
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (response != null) {
//					response.close();
//				}
//				if (httpClient != null) {
//					httpClient.close();
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return responseContent;
//	}
	private void updateYuMingList(HttpPost httpPost){
		CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        try {  
            httpClient = HttpClients.createDefault(); 
            response = httpClient.execute(httpPost); 
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
	}
	private List<Map<String,Object>> getYuMingList(HttpGet httpGet){
		
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String return_str = null;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			httpClient = HttpClients.createDefault();
			httpGet.setConfig(requestConfig);
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			return_str = EntityUtils.toString(entity, "UTF-8");
			//转json。json转list
			JSONArray jArray = JSONArray.parseArray(return_str);
			if(jArray!=null && jArray.size()>0){
				for(int i=0;i<jArray.size();i++){
					Map<String,Object> map = new HashMap<String,Object>();
					String yumingStr = jArray.get(i).toString();
					JSONObject jObject = JSONObject.parseObject(yumingStr);
					map.put("name", jObject.get("name")+"");
					map.put("address", jObject.get("address")+"");
					map.put("currentaddress", jObject.get("currentaddress")+"");
					map.put("status", jObject.get("status")+"");
					map.put("areacode", jObject.get("areacode")+"");
					list.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	private ResultAddress sendHttpsGet(HttpGet httpGet) {
		ResultAddress ra = new ResultAddress();
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		int status = 0;
		try {
			httpClient = HttpClients.createDefault();
			httpGet.setConfig(requestConfig);
			response = httpClient.execute(httpGet);
			status = response.getStatusLine().getStatusCode();
			ra.setStatusCode(status);
			if(status==200){
				ra.setLocation("");
			}else{
				String location = response.getFirstHeader("Location").getValue();
				//System.out.println(response.getFirstHeader("Location"));
				ra.setLocation(location);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ra;
	}
}